package com.yaodian100.crm.cs.service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;

import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.crm.cs.entity.QuestionAttach;

public class QuestionAttachServiceImpl extends DomainServiceImpl<QuestionAttach> implements QuestionAttachService {
	@Override
	@Transactional(readOnly = false)
	public void saveAttach(String questionId,ArrayList<byte[]> attach, ArrayList<String> attachFileName) throws CoreException {
		if (attach == null || attachFileName == null) return;
		String relPath = "/" + DateUtil.convertDateToString("yyyyMMdd", new Date()) + "/"; 
		for (int i=0;i<attach.size();i++) {
			if (attach.get(i) == null) continue;
			String filename = questionId + "-" + (i+1) + this.getFileExt(attachFileName.get(i));
			QuestionAttach att = new QuestionAttach();
			att.setQuestionId(questionId);
			att.setFileUri(QuestionAttachService.ATTACH_FILE_WEB_PATH + relPath + filename);
			super.save(att);
			
			this.saveFile(attach.get(i), QuestionAttachService.ATTACH_FILE_PATH + "/" + relPath + filename);
		}
	}
	
	private String getFileExt(String filename) {
		int index = filename.lastIndexOf(".");
		if (index != -1) {
			return filename.substring(index);
		} else {
			return "";
		}
	}
	
	private void saveFile(byte[] src,String dest) throws CoreException {
		FileOutputStream out = null;
		ByteArrayInputStream in = null;
		File destFile = new File(dest);
		destFile.getParentFile().mkdirs();
		try {
			out = new FileOutputStream(destFile);
			in = new ByteArrayInputStream(src);
			byte[] b = new byte[256];
			while (in.read(b) != -1) {
				out.write(b);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new CoreException("QuestionAttachService:"+e.getMessage(),e);
		} finally {
			try {
				in.close();
			} catch (Exception e) {}
			try {
				out.close();
			} catch (Exception e) {}
		}
	}
}
